//
//  NSPrivateAlbumViewController.m
//  Meboo
//
//  Created by kyo on 2024/5/28.
//

#import "NSPrivateAlbumViewController.h"
#import "NSPrivateNavView.h"
#import "NSPhotoCameraCell.h"
#import "NSPhotoImageCell.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "GXPHKitTool.h"
#import "NSPrivatePhotoModel.h"
#import "NSPrivatePhotoBrowser.h"
#import "NSPrivateGuideView.h"
#import "FirebaseCore/FirebaseCore.h"
#import "FirebaseStorage/FirebaseStorage-Swift.h"
#import "NSPrivateNullView.h"
@interface NSPrivateAlbumViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
UIImagePickerControllerDelegate,
GKPhotoBrowserDelegate
>
//背景图
@property (nonatomic, strong) UIImageView *backImageView;
//相册
@property (nonatomic , strong) UICollectionView *collectionView;
//头部组件
@property (nonatomic , strong) NSPrivateNavView *privateNavView;
//相册asset数组
@property (nonatomic , strong) NSMutableArray *dataArr;
//引导视图
@property (nonatomic , strong) NSPrivateGuideView *privateGuideView;
//空视图
@property (nonatomic , strong) NSPrivateNullView *privateNullView;
//防截屏
@property (nonatomic, strong) UIView *secView;
@property (nonatomic, assign) NSInteger countNum;
@property (nonatomic , assign) BOOL isUpLoading;
@end

@implementation NSPrivateAlbumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HEXS(@"ffffff");
    [self setupUI];
    [self getPrivateData];
    [self setupNotification];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)setupNotification {
    [MBNotificationCenter addObserver:self selector:@selector(uploadBegin) name:REGISTER_UPLOADPHOTO_BEGIN object:nil];
    [MBNotificationCenter addObserver:self selector:@selector(uploadEnd) name:REGISTER_UPLOADPHOTO_END object:nil];
    [MBNotificationCenter addObserver:self selector:@selector(uploadFail) name:REGISTER_UPLOADPHOTO_FAIL object:nil];
}

- (void)uploadBegin {
    self.countNum = 0;
    self.isUpLoading = YES;
    [NSTimer scheduledTimerWithTimeInterval:1
                                     target:self
                                   selector:@selector(startImageRotate:)
                                   userInfo:nil
                                    repeats:YES];
    [MBProgressHUD showActivityMessageInWindow:@"upLoding..."];
}

- (void)uploadEnd {
    self.isUpLoading = NO;
    [MBProgressHUD hideHUD];
    [MBProgressHUD showSuccessMessage:@"upload success"];
    [self getPrivateData];
}

- (void)uploadFail {
    self.isUpLoading = NO;
    [MBProgressHUD hideHUD];
    [MBProgressHUD showErrorMessage:@"upLoad fail"];
}

-(void)startImageRotate:(NSTimer *)timer {
    //30秒超时
    if (self.countNum == 30 && self.isUpLoading) {
        self.isUpLoading = NO;
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"time out"];
        [timer invalidate];
    } else if (!self.isUpLoading) {
        self.isUpLoading = NO;
        [timer invalidate];
    } else {
        self.countNum ++;
    }
}

#pragma mark - Private Method
//获取隐私图片
- (void)getPrivateData {
    __WeakSelf
    [[MBChatDataManager sharedManager] getPrivatePhoteList:^(BOOL success) {
        if (success) {
            [weakSelf.collectionView reloadData];
            [weakSelf resetNullData];
        }
    }];
}

- (void)resetNullData {
    if ([MBChatDataManager sharedManager].privateDataArr.count == 0) {
        self.privateNullView.hidden = NO;
        self.collectionView.hidden = YES;
    } else {
        self.privateNullView.hidden = YES;
        self.collectionView.hidden = NO;
    }
}

#pragma mark - Action
- (void)albumAction {
    //从相册中获取图片
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.videoMaximumDuration = 59;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie, nil];
    picker.delegate = self;
    [self.currentViewController presentViewController:picker animated:YES completion:^{}];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:NO completion:nil];
    __WeakSelf
    UIImage *editedImage = info[UIImagePickerControllerOriginalImage];
    PHAsset *asset = info[UIImagePickerControllerPHAsset];
    [self.dataArr removeAllObjects];
    GKPhoto *data = [GKPhoto new];
    if (editedImage) {
        if (asset != nil) {
            data.imageAsset = asset;
        } else {
            data.image = editedImage;
        }
    } else {
        if (asset != nil) {
            data.videoAsset = asset;
        } else {
            NSURL *selectUrl = info[UIImagePickerControllerMediaURL];
            data.videoUrl = selectUrl;
        }
    }
    [self.dataArr addObject:data];
    NSPrivatePhotoBrowser *browser = [NSPrivatePhotoBrowser photoBrowserWithPhotos:self.dataArr currentIndex:0];
    browser.showStyle = GKPhotoBrowserShowStyleZoom;
    browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
    browser.animDuration = 0.1;
    browser.isScreenRotateDisabled = YES;
    browser.delegate = self;
    if (!editedImage) {
        browser.videoLength = asset.duration;
    }
    browser.sendBlock = ^(BOOL success) {
        if (success) {
            [weakSelf getPrivateData];
        }
    };
    [browser showFromVC:self];
}

#pragma mark -- collectionView  delegate datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [MBChatDataManager sharedManager].privateDataArr.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        NSPhotoCameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NSPhotoCameraCell" forIndexPath:indexPath];
        return cell;
    } else {
        NSPhotoImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NSPhotoImageCell" forIndexPath:indexPath];
        NSPrivatePhotoModel *model = [MBChatDataManager sharedManager].privateDataArr[indexPath.row-1];
        cell.privateModel = model;
        return cell;
    }
}

//设置每个section的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(MBHeightScale(10), MBWidthScale(3), MBHeightScale(10), MBWidthScale(3));
}

//设置列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return MBWidthScale(3);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return MBWidthScale(3);
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((ScreenWidth-MBWidthScale(13))/3, (ScreenWidth-MBWidthScale(13))/3);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
//        [self.collectionView reloadData];
        [self albumAction];
    } else {
        NSPrivatePhotoModel *model = [MBChatDataManager sharedManager].privateDataArr[indexPath.row-1];
        [self.dataArr removeAllObjects];
        GKPhoto *data = [GKPhoto new];
        if (model.videoLength.length == 0) {
            data.url = [NSURL URLWithString:model.imageUrl];
        } else {
            data.videoUrl = [NSURL URLWithString:model.imageUrl];
        }
        [self.dataArr addObject:data];
        NSPrivatePhotoBrowser *browser = [NSPrivatePhotoBrowser photoBrowserWithPhotos:self.dataArr currentIndex:0];
        browser.showStyle = GKPhotoBrowserShowStyleZoom;
        browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
        browser.animDuration = 0.1;
        browser.isScreenRotateDisabled = YES;
        browser.isFromAlum = NO;
        if (model.videoLength.length == 0) {
            browser.videoLength = [model.videoLength integerValue];
        }
        
        [browser showFromVC:self];
        /**
         埋点
         点击私密相册任意照片/视频Chat_PrivateAlbum_P/V
         */
        [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_PrivateAlbum_P"];
    }
}

#pragma mark -- GKPhotoBrowserDelegate
- (void)photoBrowser:(GKPhotoBrowser *)browser singleTapWithIndex:(NSInteger)index {
    for (UIView *view in browser.view.subviews) {
        if (view.tag > 1000) {
            view.hidden = YES;
        }
    }
}

//获取视频的缩略图(第一帧)
- (UIImage *)getThumbnailImage:(NSURL *)videoUrl {
    UIImage *theImage = nil;
     AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoUrl options:nil];
     AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
     generator.appliesPreferredTrackTransform = YES;
     NSError *err = NULL;
     CMTime time = CMTimeMake(1, 60);
     CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:&err];

     theImage = [[UIImage alloc] initWithCGImage:imgRef];
     CGImageRelease(imgRef);
     return theImage;
}

- (UIView *)getBgView{
    UITextField *bgTextField = [[UITextField alloc] init];
    [bgTextField setSecureTextEntry:true];
    
    UIView *bgView = bgTextField.subviews.firstObject;
    [bgView setUserInteractionEnabled:true];
    bgView.backgroundColor = UIColor.clearColor;
    return bgView;
}


#pragma mark - UI
- (void)setupUI {
    
    [self.view addSubview:self.secView];
    [self.secView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.secView addSubview:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.secView addSubview:self.privateNavView];
    [self.privateNavView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(StatusBarAndNavigationBarHeight);
        make.right.left.top.equalTo(self.view);
    }];
    
    [self.secView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.privateNavView.mas_bottom).offset(MBHeightScale(20));
        make.right.left.bottom.equalTo(self.view);
    }];
    
    [self.secView addSubview:self.privateNullView];
    [self.privateNullView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.privateNavView.mas_bottom).offset(MBHeightScale(20));
        make.right.left.bottom.equalTo(self.view);
    }];
    
    [self.secView addSubview:self.privateGuideView];
    [self.privateGuideView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
//    MBUserAccount *account = [MBUserAccount defaultAccount];
//    account.isShowGuide = YES;
//    [MBUserAccount saveAccount:account];
}

#pragma mark - Setter && Getter

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = UIColor.clearColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.hidden = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[NSPhotoCameraCell class] forCellWithReuseIdentifier:@"NSPhotoCameraCell"];
        [_collectionView registerClass:[NSPhotoImageCell class] forCellWithReuseIdentifier:@"NSPhotoImageCell"];
    }
    return _collectionView;
}

- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"home_back_image");
    }
    return _backImageView;
}

- (NSPrivateNavView *)privateNavView {
    if (!_privateNavView) {
        _privateNavView = [NSPrivateNavView new];
    }
    return _privateNavView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (NSPrivateGuideView *)privateGuideView {
    if (!_privateGuideView) {
        __WeakSelf
        _privateGuideView = [NSPrivateGuideView new];
        _privateGuideView.hidden = [MBUserAccount defaultAccount].isVip;
        _privateGuideView.nullBlock = ^{
            [weakSelf resetNullData];
        };
    }
    return _privateGuideView;
}

- (NSPrivateNullView *)privateNullView {
    if (!_privateNullView) {
        __WeakSelf
        _privateNullView = [NSPrivateNullView new];
        _privateNullView.addBlock = ^{
            [weakSelf albumAction];
        };
    }
    return _privateNullView;
}

- (UIView *)secView {
    if (!_secView) {
        _secView = [self getBgView];
    }
    return _secView;
}
@end

